package com.kaibes.web.thymeleaf;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.context.IContext;

import com.kaibes.core.base.util.LocalDateTimeUtils;

@Service
public class ThymeleafService {

    @Autowired
    private ThymeleafConfig thymeleafConfig;
    
    private final static TemplateEngine ENGINE = new TemplateEngine();
    
    public Map<String, Object> getModel(Map<String, Object> dataModel) {
        dataModel.putAll(thymeleafConfig.getBaseModel());
    	dataModel.putAll(thymeleafConfig.getStaticVariables());
        // dateTime
        dataModel.put("dateTime", LocalDateTime.now());
        dataModel.put("dateTime1", LocalDateTimeUtils.format(LocalDateTime.now()));
        dataModel.put("dateTime2", LocalDateTimeUtils.format(LocalDateTime.now(), "yyyy年MM月dd日 HH:mm:ss"));
        return dataModel;
    }
    
    public Map<String, Object> getModel() {
        return getModel(new HashMap<String, Object>());
    }
    
    public String process(String template, Map<String, Object> dataModel) {
        Context context = new Context();
        context.setVariables(dataModel);
        return ENGINE.process(template, context);
    }
    
    public String process(String template, IContext context) {
        return ENGINE.process(template, context);
    }

}
